// axios二次封装
import axios from 'axios'
import { ElMessage } from 'element-plus'

import useUserStore from '@/store/modules/user'
// 1 利用axios对象的create方法，创建axios实现配置封装
let request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 360000, //6分钟超时
})

//  2 request配置
request.interceptors.request.use((config) => {
  let userStore = useUserStore()

  if (userStore.token) {
    config.headers.token = userStore.token
  }
  return config
})
// 3 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    return Promise.reject(error)
    // 定义一个变量
    let message = ''
    let status = error.response.status
    switch (status) {
      case 400:
        message = '请求错误'
        break
      case 401:
        message = '未授权，请登录'
        break
      case 403:
        message = '拒绝访问'
        break
      case 404:
        message = `请求地址出错: ${error.response.config.url}`
        break
      case 408:
        message = '请求超时'
        break
      case 500:
        message = '服务器内部错误'
        break
      case 501:
        message = '服务未实现'
        break
      default:
        message = '网络出现问题'
        break
    }
    // 提示错误信息
    ElMessage({
      message,
      type: 'error',
    })

    return Promise.reject(error)
  },
)

export default request
